package com.zjeav.lingjiao.ui.personCenter;

import android.annotation.SuppressLint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dalimao.corelibrary.pullrefresh.BGANormalRefreshViewHolder;
import com.dalimao.corelibrary.pullrefresh.BGARefreshLayout;
import com.dalimao.corelibrary.pullrefresh.PowerfulRecyclerView;
import com.dalimao.corelibrary.pullrefresh.TipView;
import com.dalimao.corelibrary.swipeback.SwipeBackActivity;
import com.dalimao.corelibrary.utils.NetWorkUtils;
import com.dalimao.corelibrary.view.SelfDialog;
import com.maning.mndialoglibrary.MProgressDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.baseBean.BookList;
import com.zjeav.lingjiao.base.baseBean.Order;
import com.zjeav.lingjiao.base.baseBean.PayResult;
import com.zjeav.lingjiao.base.config.BaseConfig;
import com.zjeav.lingjiao.base.request.OrderQuery;
import com.zjeav.lingjiao.base.request.OrderSubscribeRequest;
import com.zjeav.lingjiao.base.response.OrderQueryResponse;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.book.BookDetailContract;
import com.zjeav.lingjiao.ui.book.BookDetialActivity;
import com.zjeav.lingjiao.ui.book.OrderAdapter;
import com.zjeav.lingjiao.ui.personCenter.view.PersonInfoContract;
import com.zjeav.lingjiao.ui.presenter.BookPresenter;

import java.util.ArrayList;
import java.util.Map;

/**
 * 购买记录
 */
public class OrderActivity extends SwipeBackActivity implements PersonInfoContract.OrderView,
        BGARefreshLayout.BGARefreshLayoutDelegate, View.OnClickListener, BookDetailContract.PayView {

    private TipView tipView;
    private BGARefreshLayout mRefreshLayout;
    private PowerfulRecyclerView rv_orders;
    private boolean ispull = true; //是否是下拉刷新
    private IWXAPI api;
    private OrderAdapter adapter;
    private PersonPresenter personPresenter;
    private ArrayList<Order> orders = new ArrayList<>();
    private PopupWindow popupWindow;
    private View contentView;
    private RelativeLayout dialog_zhifubao, dialog_wechat;//;
    private ImageView recharge_zhifubao_cb, recharge_wechat_cb, recharge_dialog_close;
    private TextView dialog_confirm_pay, pay_price;
    private int PayType = 0;//0:weixin 1:zhifubao
    private SelfDialog selfDialog;
    Order order;
    BookPresenter bookPresenter;
    private static final int SDK_PAY_FLAG = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_list_layout);
        init();
    }

    /**
     * 显示popupWindow
     */
    private void showPopwindow() {
        //加载弹出框的布局
        contentView = LayoutInflater.from(OrderActivity.this).inflate(
                R.layout.dialog_pay, null);
        dialog_zhifubao = contentView.findViewById(R.id.dialog_zhifubao);
        pay_price = contentView.findViewById(R.id.pay_price);
        dialog_zhifubao.setOnClickListener(this);
        recharge_zhifubao_cb = contentView.findViewById(R.id.recharge_zhifubao_cb);
        recharge_dialog_close = contentView.findViewById(R.id.recharge_dialog_close);
        recharge_dialog_close.setOnClickListener(this);
        dialog_wechat = contentView.findViewById(R.id.dialog_wechat);
        recharge_wechat_cb = contentView.findViewById(R.id.recharge_wechat_cb);
        dialog_wechat.setOnClickListener(this);
        dialog_confirm_pay = contentView.findViewById(R.id.dialog_confirm_pay);
        dialog_confirm_pay.setOnClickListener(this);
        popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(true);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画，指定刚才定义的style
        popupWindow.setAnimationStyle(R.style.recharge_pay_dialog);

        // 按下android回退物理键 PopipWindow消失解决

    }
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, "支付成功: " + payResult);
                        popupWindow.dismiss();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showAlert(PayDemoActivity.this, "支付失败: " + payResult);
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };
    private void init() {
        bookPresenter = new BookPresenter(this);
        tipView = findViewById(R.id.tip_view);
        mRefreshLayout = findViewById(R.id.refresh_layout);
        rv_orders = findViewById(R.id.rv_orders);
        api = WXAPIFactory.createWXAPI(this, BaseConfig.APP_ID);
        adapter = new OrderAdapter(this);
        adapter.setEnableLoadMore(true);
        mRefreshLayout.setDelegate(this);
        rv_orders.setLayoutManager(new GridLayoutManager(this, 1));
        // 设置下拉刷新和上拉加载更多的风格     参数1：应用程序上下文，参数2：是否具有上拉加载更多功能
        BGANormalRefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, false);
        // 设置下拉刷新
        refreshViewHolder.setRefreshViewBackgroundColorRes(R.color.color_F3F5F4);//背景色
        refreshViewHolder.setPullDownRefreshText(UIUtils.getString(R.string.refresh_pull_down_text));//下拉的提示文字
        refreshViewHolder.setReleaseRefreshText(UIUtils.getString(R.string.refresh_release_text));//松开的提示文字
        refreshViewHolder.setRefreshingText(UIUtils.getString(R.string.refresh_ing_text));//刷新中的提示文字
        // 设置下拉刷新和上拉加载更多的风格
        mRefreshLayout.setRefreshViewHolder(refreshViewHolder);
        mRefreshLayout.shouldHandleRecyclerViewLoadingMore(rv_orders);
        rv_orders.setAdapter(adapter);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MProgressDialog.showProgress(OrderActivity.this, "订单查询...");
                order = (Order) adapter.getItem(position);
                bookPresenter.queryOrder(new OrderQuery(order.getOrderid()));
            }
        });
        personPresenter = new PersonPresenter(this);
        personPresenter.getOrders();
        showPopwindow();

    }

    @Override
    public void showOrders(ArrayList<Order> orders) {
        if (ispull) {
            tipView.show("加载数据成功");
        }

        if (orders.size() <= 0) {
            adapter.loadMoreEnd();
            tipView.show("暂无数据");
            return;
        }
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新
        this.orders.addAll(orders);
        adapter.replaceData(this.orders);
    }

    @Override
    public void showError(Throwable throwable) {
        if (ispull) {
            tipView.show("数据加载出错");
        }
        mRefreshLayout.endRefreshing();// 加载完毕后在 UI 线程结束下拉刷新
    }


    /**
     * 下拉刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        ispull = true;
        if (!NetWorkUtils.isNetworkAvailable(this)) {
            //网络不可用弹出提示
            tipView.show();
            if (mRefreshLayout.getCurrentRefreshStatus() == BGARefreshLayout.RefreshStatus.REFRESHING) {
                mRefreshLayout.endRefreshing();
            }
            return;
        }
        orders.clear();
        personPresenter.getOrders();
        adapter.loadMoreComplete();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.pay_txt:
//                pay_price.setText("￥: " + bookDetailResponse.getPrice());
//                popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
//                break;
            case R.id.dialog_wechat:
                PayType = 0;
                recharge_wechat_cb.setBackground(getResources().getDrawable(R.mipmap.choos_sel));
                recharge_zhifubao_cb.setBackground(getResources().getDrawable(R.mipmap.choos_normal));
                break;
            case R.id.dialog_zhifubao:
                PayType = 1;
                recharge_zhifubao_cb.setBackground(getResources().getDrawable(R.mipmap.choos_sel));
                recharge_wechat_cb.setBackground(getResources().getDrawable(R.mipmap.choos_normal));
                break;
            case R.id.dialog_confirm_pay:
//                if (PayType == 1) {
//                    Toast.makeText(this, "暂不支持支付宝支付", Toast.LENGTH_SHORT).show();
//                } else {
//                    ArrayList<BookList> books = new ArrayList();
//                    books.add(new BookList(order.getId(), 1, bookDetailResponse.getPrice()));
//                    OrderSubscribeRequest request = new OrderSubscribeRequest("微信", "", books);
//                    shopPresenter.getOder(request);
//                    action_txt.setEnabled(false);
//                    Toast.makeText(this, "获取订单中...", Toast.LENGTH_SHORT).show();
//                    action_txt.setEnabled(true);
//                }
                break;
            case R.id.recharge_dialog_close:
                popupWindow.dismiss();
                break;
        }
    }

    @Override
    public void QueryPay(final OrderQueryResponse queryResponse) {
        MProgressDialog.dismissProgress();
        if (queryResponse.getPaymethod().equals("微信")) {
            api.registerApp(BaseConfig.APP_ID);
            PayReq req = new PayReq();
//            Log.d("order", JSON.toJSONString(response) + "");
            if (queryResponse.getBusinessinfo() != null) {
                req.appId = queryResponse.getBusinessinfo().getAppid();
                req.partnerId = queryResponse.getBusinessinfo().getPartnerId();
                req.prepayId = queryResponse.getBusinessinfo().getPrepayId();
                req.nonceStr = queryResponse.getBusinessinfo().getNonceStr();
                req.timeStamp = queryResponse.getBusinessinfo().getTimeStamp();
                req.sign = queryResponse.getBusinessinfo().getSign();
            }
            req.packageValue = "Sign=WXPay";
            req.extData = "app data";// optional
//        Toast.makeText(this, "正常调起支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);
        }else {
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(OrderActivity.this);
                    Map<String, String> result = alipay.payV2(queryResponse.getBusinessinfo().getOrderString(), true);
                    Log.i("msp", result.toString());

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();
//            Toast.makeText(this, "暂不支持支付宝支付", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void ShowFail(Throwable throwable) {
        MProgressDialog.dismissProgress();
    }
}
